package servlet.rool;

import net.sf.json.JSONObject;
import pojo.Admin;
import service.AdminService;
import service.impl.AdminServiceImpl;
import util.ExcelUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 从Excel导入用户数据到数据库中的servlet
 */
@WebServlet(value = "/AdminImportServlet")
public class AdminImportServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //定义标识符
        request.setCharacterEncoding("UTF-8");
        String path = "C:\\Users\\Dell\\Downloads\\" + request.getParameter("file");
        //调用读取excel的方法，并得到一个返回值集合
        List<String> list = ExcelUtil.readByFilePath(path);
        if (list == null) {
            JSONObject json=new JSONObject();
            json.put("msg","导入失败!");
            PrintWriter out = response.getWriter();
            out.print(json);
            return;
        }
        int bo = 0;
        //实例化Adminservice对象
        AdminService as=new AdminServiceImpl();
        //循环遍历集合，并得到字符串，然后切割字符串，获得分类类型
        for (int i = 1; i < list.size(); i++){
            Admin admin=new Admin();
            String[] data = list.get(i).split("`");
            //通过set方法，向admin对象里写入属性
            admin.setAdName(data[0]);
            admin.setAdAccount(data[1]);
            admin.setAdSex(data[2].equals("男") ? 1:0);
            admin.setAdPhone(data[3]);
            admin.setAdEmail(data[4]);
            admin.setAdPassword("123456");
            bo=as.inseAdmin(admin);
            if(bo>0){
                bo++;
            }
        }
        JSONObject json=new JSONObject();
        if(bo>0){
            json.put("msg","导入成功");
        }else {
            json.put("msg","导入失败");
        }
        PrintWriter out=response.getWriter();
        out.print(json);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
        doGet(request, response);
    }
}
